package picture

import (
	"fmt"
	"server/model"
	"server/model/database"

	"github.com/gin-gonic/gin"
)

var pictures []model.Picture

func GerRoute(rg *gin.RouterGroup) {
	picture := rg.Group("/picture")

	picture.GET("", getAllPictureId)
	picture.GET("/", getAllPictureId)
	picture.POST("/", addPicture)
	picture.GET("/:id/", getPicture)
}

func getPicture(c *gin.Context) {
	id := c.Param("id")
	var data *model.Picture



	for _, picture := range pictures {
		if picture.Id == id {
			data = &picture
			break
		}
	}

	if data != nil {
		c.JSON(200, gin.H{
			"status": "got",
			"data":   *data,
		})
	} else {
		c.JSON(200, gin.H{
			"status": "got",
			"data":   nil,
		})
	}

}

func getAllPictureId(c *gin.Context) {
	ids := make([]string, 0)


	pictures = database.Instance.FindPictures()

	for _, picture := range pictures {
		ids = append(ids, picture.Id)
	}

	c.JSON(200, gin.H{
		"status": "got",
		"data":   ids,
	})
}

func addPicture(c *gin.Context) {

	var picture model.Picture
	err := c.BindJSON(&picture)

	var message = ""
	if err != nil {
		message = "没有获取到参数"
	} else {
		//pictures = append(pictures, &picture)
		database.Instance.AddPicture(picture)
		message = fmt.Sprintln(picture)
	}
	//pictures = append(pictures, &model.Picture{
	//	Name: c.PostForm("Name"),
	//	Tags: c.PostForm("Tags"),
	//	Description: c.PostForm("Description"),
	//	Image: c.PostForm("Image"),
	//	Id: c.PostForm("Id"),
	//})
	//
	//fmt.Println(pictures)

	//message := fmt.Sprint(pictures[len(pictures) - 1])

	c.JSON(200, gin.H{
		"status":  "posted",
		"message": message,
	})
}
